package com.soxing.webrain.brush.controller;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.soxing.webrain.brush.common.util.JwtUtil;
import com.soxing.webrain.brush.dao.entity.User;
import com.soxing.webrain.brush.dao.service.impl.UserServiceImpl;
import com.soxing.webrain.brush.domain.view.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/user")
@CrossOrigin  //解决跨域
public class LoginController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    UserServiceImpl userService;

    //login
    @PostMapping("login")
    public R login(@RequestBody User user, HttpServletRequest request) {
        String userPin = user.getUserPin();
        String password = user.getPassword();
        if (userPin == null || password == null) {
            logger.error("userNum或userPwd为空");
            return R.error().message("登录验证失败");
        }
        User userInfo = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUserPin, userPin));
        if (userInfo == null) {
            logger.error("{}不是管理员账号", userPin);
            return R.error().message("无登录权限,请联系管理员");
        }
        if (!password.equals(userInfo.getPassword())) {
            logger.error("{}密码不正确", userPin);
            return R.error().message("登录失败");
        }
//        request.getSession().setAttribute(SystemConstant.LOGIN_USER, userVo);

        Map<String,Object> claims = new HashMap<>();
        claims.put("id",userInfo.getId());
        claims.put("username",userInfo.getUserPin());
        String token = JwtUtil.genToken(claims);
        return R.ok().data("token",token).data("user",userInfo);
    }

    @RequestMapping("/logout")
    public R logout(@RequestParam String token) {

        return R.ok();
    }

    //info
    @GetMapping("info")
    public R info(@RequestParam String token) {
        Map<String,Object> claims = JwtUtil.parseToken(token);
        return R.ok().data("roles","[admin]").data("name",claims.get("username")).data("avatar","");
    }

}



